import threading
from lib import helper, resp
from lib.snowflake import Snowflake
from models.user_chapter_field import UserChapterField
from models.user_novel import UserNovel


class ChapterFieldService:

    local_data = threading.local()
    local_data.test_list = []

    def __init__(self) -> None:
        self.local_data.test_list = []
        pass
    
    def field_list(self):
        list = UserChapterField.table().where("IsValid", 1).get()
        return resp.ret_obj({"List": list})

    
    def field_save(self, novel_id=0, data: dict = {}):
        t = UserChapterField.table()
        info = t.where("FieldId", novel_id).first()
        if info:
            rs = t.update(helper.update_data_time(data))
        else:
            data["FieldId"] = Snowflake.unique_id()
            rs = UserChapterField.table().insert(helper.add_data_time(data))
        if not rs:
            return resp.ret_failed()
        return resp.ret_obj()

    def field_delete(self, novel_id):
        rs = UserChapterField.table().where('FieldId', novel_id).update({"IsValid": 0})
        if rs:
            return resp.ret_obj()
        return resp.ret_failed()